package com.bnlr.lrparking.adapter;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.bnlr.lrparking.constant.LrConstant;
import com.bnlr.lrparking.constant.Urls;
import com.bumptech.glide.Glide;
import com.bnlr.lrparking.app.Application;
import com.bnlr.lrparking.R;
import com.bnlr.lrparking.appui.stall.InvestActivity;
import com.bnlr.lrparking.appui.order.OrderPayActivity;
import com.bnlr.lrparking.app.AppConfig;
import com.bnlr.lrparking.model.InvestRecodrData;
import com.bnlr.lrparking.model.InvestRecodrM;
import com.bnlr.lrparking.util.CommonUtil;
import com.bnlr.nohttp.CallServer;
import com.bnlr.nohttp.CustomHttpListener;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.rest.Request;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 投资记录 适配器
 *
 * @author hp
 * @date 2017/8/23
 */

public class InvestRecodrAdapter extends BaseAdapter {

    public Request<String> mRequest;
    private Context mcontext;
    private List<InvestRecodrData> list;
    private LayoutInflater inflater;
    private Intent intent;


    public InvestRecodrAdapter(Context context, List<InvestRecodrData> list) {
        super();
        this.mcontext = context;
        this.list = list;
        inflater = LayoutInflater.from(mcontext);
    }

    @Override
    public int getCount() {
        if (list != null) {
            return list.size();
        }
        return 0;
    }

    @Override
    public Object getItem(int i) {
        return list.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View convertView, ViewGroup viewGroup) {
        final ViewHoder hoder;
        if (convertView == null) {
            hoder = new ViewHoder();
            convertView = inflater.inflate(R.layout.item_inverstr, null);
            hoder.img_invest = (ImageView) convertView.findViewById(R.id.img_invest);
            hoder.order_number = (TextView) convertView.findViewById(R.id.order_number);
            hoder.tv_invest_type = (TextView) convertView.findViewById(R.id.tv_invest_type);
            hoder.tv_invest_name = (TextView) convertView.findViewById(R.id.tv_invest_name);
            hoder.tv_invest_number = (TextView) convertView.findViewById(R.id.tv_invest_number);
            hoder.tv_invest_time = (TextView) convertView.findViewById(R.id.tv_invest_time);
            hoder.image_type = (ImageView) convertView.findViewById(R.id.image_type);
            hoder.order_type = (TextView) convertView.findViewById(R.id.order_type);
            hoder.tv_closeorder = (TextView) convertView.findViewById(R.id.tv_closeorder);
            hoder.tv_order_pay = (TextView) convertView.findViewById(R.id.tv_order_pay);
            hoder.tv_shared_values = (TextView) convertView.findViewById(R.id.tv_shared_values);
            convertView.setTag(hoder);
        } else {
            hoder = (ViewHoder) convertView.getTag();
        }
        final InvestRecodrData bean = list.get(i);
        Glide.with(mcontext)
                .load(R.mipmap.aaa)
                .placeholder(R.mipmap.img_stall_error)
                .error(R.mipmap.img_stall_error)
                .into(hoder.img_invest);
        hoder.order_number.setText("订单号：" + bean.getOrderNo());
        hoder.tv_invest_type.setText(bean.getOwnerType());
        hoder.tv_invest_name.setText(bean.getAddress());
        hoder.tv_invest_number.setText("车位编号：" + bean.getNumber());
        hoder.tv_invest_time.setText("下单时间：" + bean.getCreateTime());
        hoder.tv_shared_values.setText(bean.getAmount()
        );

        /**
         * 待付款
         */
        if (bean.getStatus().equals("未支付")) {
            hoder.order_type.setText("待付款");
            hoder.order_type.setTextColor(mcontext.getResources().getColor(R.color.order_type));
            hoder.image_type.setImageResource(R.mipmap.record_unpaid);
            hoder.tv_closeorder.setVisibility(View.VISIBLE);
            hoder.tv_order_pay.setVisibility(View.VISIBLE);
            hoder.tv_order_pay.setText("付款");
            hoder.tv_order_pay.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    intent = new Intent(mcontext, OrderPayActivity.class);
                    intent.putExtra("money", bean.getAmountMoney());
                    intent.putExtra("orderNo", bean.getOrderNo());
                    intent.putExtra("id", bean.getUserParkSpaceId());
                    mcontext.startActivity(intent);
                    //是从哪个列表去支付界面的
                    AppConfig.getInstance().putString("isList", "1");
                    //格式化时间
                    SimpleDateFormat d = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    //按以上格式 将当前时间转换成字符串
                    String nowtime = d.format(new Date());
                    //最后时间
                    String testtime = bean.getLastPayTime();
                    try {
                        //当前时间减去测试时间 这个的除以1000得到秒，相应的60000得到分，3600000得到小时
                        long result = (d.parse(testtime).getTime() - d.parse(nowtime).getTime());
                        //用户名
                        AppConfig.getInstance().putString("dataResult", result + "");
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
            });

            //取消订单
            hoder.tv_closeorder.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    View view3 = View.inflate(mcontext,
                            R.layout.setting_custom_dialog, null);
                    // 对话框
                    final Dialog dialog2 = new AlertDialog.Builder(mcontext, R.style.NativeDialog)
                            .create();
                    dialog2.show();
                    dialog2.getWindow().setWindowAnimations(R.style.dialog_anim_style);
                    dialog2.getWindow().setContentView(view3);
                    TextView text_phone = (TextView) view3.findViewById(R.id.text_phone);
                    text_phone.setText("确定要取消该订单吗");
                    // 取消按钮
                    TextView btn_Cancel2 = (TextView) view3.findViewById(R.id.cancle);
                    btn_Cancel2.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            dialog2.dismiss();
                        }
                    });
                    // 确定按钮
                    TextView btn_OK2 = (TextView) view3.findViewById(R.id.sure);
                    btn_OK2.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            dialog2.dismiss();
                            cancelOrder(bean, bean.getOrderNo());
                        }
                    });

                }
            });
            /**
             * 已投资
             */
        } else if (bean.getStatus().equals("交易成功")) {
            hoder.order_type.setText("投资成功");
            hoder.order_type.setTextColor(mcontext.getResources().getColor(R.color.order_type));
            hoder.image_type.setImageResource(R.mipmap.record_pay);
            hoder.tv_closeorder.setVisibility(View.GONE);
            hoder.tv_order_pay.setVisibility(View.VISIBLE);
            hoder.tv_order_pay.setText("追加投资");
            hoder.tv_order_pay.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    intent = new Intent(mcontext, InvestActivity.class);
                    intent.putExtra("number", bean.getNumber());
                    intent.putExtra("sellingprice", bean.getSellingPrice());
                    intent.putExtra("monthCount", bean.getMaxMonthCount());
                    intent.putExtra("id", bean.getUserParkSpaceId());
                    mcontext.startActivity(intent);
                    //是从哪个列表去支付界面的
                    AppConfig.getInstance().putString("isList", "0");
                }
            });
            /**
             * 已过期
             */
        } else if (bean.getStatus().equals("交易终止")) {
            hoder.order_type.setText("投资过期");
            hoder.order_type.setTextColor(mcontext.getResources().getColor(R.color.gray03_color));
            hoder.image_type.setImageResource(R.mipmap.record_overdue);
            hoder.tv_closeorder.setVisibility(View.GONE);
            hoder.tv_order_pay.setVisibility(View.VISIBLE);
            hoder.tv_order_pay.setText("去投资");
            hoder.tv_order_pay.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    intent = new Intent(mcontext, InvestActivity.class);
                    intent.putExtra("number", bean.getNumber());
                    intent.putExtra("sellingprice", bean.getSellingPrice());
                    intent.putExtra("monthCount", bean.getMaxMonthCount());
                    mcontext.startActivity(intent);
                    //是从哪个列表去支付界面的
                    AppConfig.getInstance().putString("isList", "0");
                }
            });
        }
        return convertView;
    }

    class ViewHoder {
        ImageView img_invest, image_type;
        TextView order_number, tv_invest_type, tv_invest_name, tv_invest_number, tv_invest_time, order_type;
        TextView tv_closeorder, tv_order_pay;
        /**
         * 应付的共享值
         */
        TextView tv_shared_values;
    }

    /**
     * 取消订单
     *
     * @param bean
     * @param orderNo
     */
    private void cancelOrder(final InvestRecodrData bean, String orderNo) {
        try {
            if (CommonUtil.isNetworkAvailable(mcontext) == 0) {
                CommonUtil.showToask(mcontext, "当前无网络连接，请检查网络设置");
                return;
            }
            mRequest = NoHttp.createStringRequest(Urls.SPACE_IP, LrConstant.POST);
            mRequest.add("action", "CancelApplyBuySpace");
            mRequest.add("phonePara", Application.DEVICE_ID);
            mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));
            mRequest.add("orderNo", orderNo);
            CallServer.getRequestInstance().add(mcontext, mRequest,
                    new CustomHttpListener<InvestRecodrM>(mcontext, true, InvestRecodrM.class) {
                        @Override
                        public void doWork(InvestRecodrM data, String code) {
                            if ("1".equals(code)) {
                                CommonUtil.showToask(mcontext, data.getMsg());
                                list.remove(bean);
                                notifyDataSetChanged();
                            }
                        }

                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {
                            try {
                                super.onFinally(obj, code, isSucceed);
                                if ("0".equals(code)) {

                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }, true);
        } catch (Exception e) {
        }
    }
}
